#!/bin/sh

#--------------------------------------------------
# Des chemins utiles
#--------------------------------------------------
mypath="`dirname "$0"`"
rsrcpath="`dirname "$mypath"`"/Resources
Appdir="`dirname "$mypath"`"
Appdir="`dirname "$Appdir"`"
Appdir="`dirname "$Appdir"`"
AtariST=$rsrcpath/AtariST

pashua_run() {
	pashua_configfile=`/usr/bin/mktemp /tmp/pashua_XXXXXXXXX`
	echo "$1" > $pashua_configfile
	mypath="`dirname "$0"`"
	pashuapath="$mypath/Pashua"
	encoding=""
	result=`"$pashuapath" $encoding $pashua_configfile | sed 's/ /;;;/g'`
	rm $pashua_configfile
	for line in $result
	do
		key=`echo $line | sed 's/^\([^=]*\)=.*$/\1/'`
		value=`echo $line | sed 's/^[^=]*=\(.*\)$/\1/' | sed 's/;;;/ /g'`		varname=$key
		varvalue="$value"
		eval $varname='$varvalue'
	done
} # pashua_run()


# Define what the dialog should be like
# Take a look at Pashua's Readme file for more info on the syntax

#----------------------------
# Description de l'interface
#----------------------------
conf="
*.transparency=0.95
*.title = Atari Construction Kit
#*.appearance = metal

chkDoApp.type = checkbox
chkDoApp.label = Atari precedent --> MacProg.app
chkDoApp.default = 0
chkDoApp.relx = 50
chkDoApp.rely = -20

chkcursor.type = checkbox
chkcursor.label = vrai curseur et non faux joystick
chkcursor.default = 0
chkcursor.relx = 50
chkcursor.rely = -20

chkHDXT.type = checkbox
chkHDXT.label = MacProg sera dans le dossier HD
chkHDXT.default = 0
chkHDXT.relx = 50
chkHDXT.rely = -20

chkdemar.type = radiobutton
chkdemar.option = Ne pas tenter d' utiliser \"hatari.sav\"
chkdemar.option = Hack1: demarrer sur \"hatari.sav\"
chkdemar.option = Hack2: utiliser \"hatari.sav\" et HD
chkdemar.default = Ne pas tenter d' utiliser \"hatari.sav\"
chkdemar.relx = 10
chkdemar.rely = -20

# Add a filesystem browser
fond.type = openbrowser
fond.label =  + Ecran .PDF en arriere-fond
#fond.default = $rsrcpath/MacApp/Contents/Resources/hatarifondw.pdf
fond.filetype = pdf PDF
fond.width = 250
fond.relx = 25
fond.rely = -15

tb.type = text
tb.default = .                                                                    ..                                                                    ..                                                                    ..                                                                    .
#tb.height = 276
#tb.width = 310
#tb.x = 340
#tb.y = 44
tb.rely = -10

# Add a popup menu
popTOS.type = popup
#popTOS.label = TOS
popTOS.width = 270
popTOS.option = Atari ST Tos 1.00 (alerte HD)
popTOS.option = Atari ST Tos 1.04
popTOS.option = Atari STE Tos 1.62
popTOS.option = Atari STE Tos 2.06
popTOS.option = Atari TT Tos 3.06
popTOS.option = Falcon Tos 4.04
popTOS.default = Atari STE Tos 1.62
popTOS.rely = -20

# Add a popup menu
popECRAN.type = popup
#popECRAN.label = ECRAN
popECRAN.width = 270
popECRAN.option = Basse resolution
popECRAN.option = overscan Spectrum 512
popECRAN.option = N&B Haute resolution
popECRAN.default = Basse resolution
popECRAN.rely = -20

# Add a popup menu
#popCLAVIER.type = popup
#popCLAVIER.label = CLAVIER
#popCLAVIER.width = 270
#popCLAVIER.option = QWERTY
#popCLAVIER.option = AZERTY.0 Alpha
#popCLAVIER.option = AZERTY.0 Numerique
#popCLAVIER.default = AZERTY.0 Alpha
#popCLAVIER.rely = -20

# Add a filesystem browser
CLAVIER.type = openbrowser
#CLAVIER.label = _______Clavier_________
CLAVIER.filetype = txt TXT
CLAVIER.default = $AtariST/AZERTY.0 Alpha.txt
CLAVIER.width = 270
CLAVIER.rely = -20

# Add a filesystem browser
DISKA.type = openbrowser
DISKA.label = _______Disquette A et B (.st ou .MSA)_________
DISKA.filetype = st ST msa MSA
DISKA.width = 260
DISKA.rely = -20

# Add a filesystem browser
DISKB.type = openbrowser
#DISKB.label = Disquette B (.st ou .MSA)
DISKB.filetype = st ST msa MSA
DISKB.width = 260
DISKB.rely = -20

# Add a filesystem browser
HDE.type = openbrowser
HDE.filetype = directory
HDE.label = ____________Disque dur (dossier )____________
#HDE.default = $AtariST/HDD
HDE.width = 260
HDE.rely = -20

# Add a filesystem browser
CART.type = openbrowser
CART.label =__________Cartouche____________ 
#CART.default = $AtariST/Cartouche
CART.width = 200
CART.rely = -15

# Add a checkbox
#chk1.type = checkbox
#chk1.label = curseur=joystick
#chk1.default = 1
#chk1.rely = -20

chkfullscreen.type = checkbox
chkfullscreen.label = fullscreen
chkfullscreen.default = 0
#chkfullscreen.relx = 150
chkfullscreen.rely = -20

chkVDI.type = checkbox
chkVDI.label = VDI 1280x848
chkVDI.default = 0
#chkVDI.relx = 150
chkVDI.rely = -20

#Add a cancel button with default label
cb.type=cancelbutton
#cb.label = Ne rien faire

# Define radiobuttons
#rb1.type = radiobutton
#rb1.label = MODELE
#rb1.option = Atari ST Tos 1.00 (alerte)
#rb1.option = Atari STE Tos 1.62
#rb1.default = Atari STE Tos 1.62
#rb1.relx = 20
#rb1.rely = -20

";
#-----------------------------------------------------------------------------------------------------------------------
#Section Image
icon=$rsrcpath"/icon.png";
conf="$conf
	     img.type = image
	     img.x = -10
	     img.y = 460
	     img.path = $icon"
bgimg=$rsrcpath"/Hatari.png";
conf="$conf
		bg.type = image
		bg.x = -10
		bg.y = 286
		bg.path = $bgimg"
#-----------------------------------------------------------------------------------------------------------------------
# FIN de la section PASHUA. On lance l'interface, on pourra traiter les donnes reues dans les variables
#-----------------------------------------------------------------------------------------------------------------------
pashua_run "$conf"

echo "  chkDoApp  = $chkDoApp"
echo "  chkcursor  = $chkcursor"
echo "  chkdemar = $chkdemar"
echo "  chkHDXT = $chkHDXT"
echo "  fond  = $fond"
echo "  popTOS  = $popTOS"
echo "  popECRAN  = $popECRAN"
echo "  CLAVIER  = $CLAVIER"
echo "  DISKA  = $DISKA"
echo "  DISKB  = $DISKB"
echo "  HDE  = $HDE"
echo "  CART  = $CART"
echo "  Fullscreen  = $chkfullscreen"
echo "  VDI  = $chkVDI"
#-----------------------------------------------------------------------------------------------------------------------
# On traite les donnes relues dans les variables
#-----------------------------------------------------------------------------------------------------------------------
if test "$cb" -eq "1"  ; then
	exit 0
fi
#==================================================================================
# On va dans Resources où on a tout préparé
#==================================================================================
AtariST=$rsrcpath/AtariST
cd $AtariST
#==================================================================================
# Création d'application autonome à partir de la dernière new.cfg créée
#==================================================================================

if test ! "$chkDoApp" -eq "0"; then
	#---------------------------------------------------------------
	# On met l'ancienne Configurations/new.cfg dans la variable app
	app=$(<CONFIGS/new.cfg)
	#---------------------------------------------------------------
	# S'il y a un dossier HD et coché "MacProg sera dans le dossier HD" on met Mac.app dedans
	#---------------------------------------------------------------
	if test ! $(grep -c -e "szHardDiskDirectory =/" <<<"$app") -eq  0  ; then 
		ligne=$(grep -e "szHardDiskDirectory =" <<<"$app")
		chaine=`cut -d= -f2 <<<"$ligne"`
		if test ! "$chkHDXT" -eq "0"; then
			target="$chaine/MacProg.app"
		else
			target="$Appdir/MacProg.app"
		fi
	fi
	#---------------------------------------------------------------
	# On copie l'application Mac prémachée
	#---------------------------------------------------------------
	cp -R "$rsrcpath/MacApp" "$target"
	#---------------------------------------------------------------
	# On ajoute l'émulateur et ses annexes
	#---------------------------------------------------------------
	#cp -R "$rsrcpath/AtariST" "$target/Contents/Resources/AtariST"
	mkdir "$target/Contents/Resources/AtariST"
	mkdir "$target/Contents/Resources/AtariST/CONFIGS"
	#mkdir "$target/Contents/Resources/AtariST/SAUVEGARDES"
	cp -R "$rsrcpath/AtariST/SAUVEGARDES" "$target/Contents/Resources/AtariST/SAUVEGARDES"
	cp -R "$rsrcpath/AtariST/Hatari.app" "$target/Contents/Resources/AtariST"
	#---------------------------------------------------------------
	# On lit dans app (ancienne new.cfg) le TOS et le clavier à copier
	#---------------------------------------------------------------
	ligne=$(grep -e "szTosImageFileName = " <<<"$app")
	tos=${ligne##*= }
	cp -R "$rsrcpath/AtariST/$tos" "$target/Contents/Resources/AtariST"
	ligne=$(grep -e "szMappingFileName = " <<<"$app")
	kb=${ligne##*= }
	cp -R "$rsrcpath/AtariST/$kb" "$target/Contents/Resources/AtariST"
	#---------------------------------------------------------------
	# On modifie l'ancienne Configurations/new.cfg copiée en /tmp/app.cfg  et on copie les disques dans MacProg.app
	#---------------------------------------------------------------
	if test ! $(grep -c -e "szDiskAFileName =/" <<<"$app") -eq  0  ; then 
		ligne=$(grep -e "szDiskAFileName =" <<<"$app")
		chaine=`cut -d= -f2 <<<"$ligne"`
		feuille=${chaine##*/}
		 app2=$(eval "sed 's^szDiskAFileName =.*$^szDiskAFileName =../AtariST/$feuille^g'<<<\"$app\"")
		app="$app2"
		cp  -R "$chaine" "$target/Contents/Resources/AtariST/"		
	fi
	if test ! $(grep -c -e "szDiskBFileName =/" <<<"$app") -eq  0  ; then 
		ligne=$(grep -e "szDiskBFileName =" <<<"$app")
		chaine=`cut -d= -f2 <<<"$ligne"`
		feuille=${chaine##*/}
		app2=$(	eval "sed 's^szDiskBFileName =.*$^szDiskBFileName =../AtariST/$feuille^g'<<<\"$app\"")
		app="$app2"
		cp  -R "$chaine" "$target/Contents/Resources/AtariST/"		
	fi
	if test ! $(grep -c -e "szCartridgeImageFileName =/" <<<"$app") -eq  0  ; then 
		ligne=$(grep -e "szCartridgeImageFileName =" <<<"$app")
		chaine=`cut -d= -f2 <<<"$ligne"`
		feuille=${chaine##*/}
		app2=$(	eval "sed 's^szCartridgeImageFileName =.*$^szCartridgeImageFileName =../AtariST/$feuille^g'<<<\"$app\"")
		app="$app2"
		cp  -R "$chaine" "$target/Contents/Resources/AtariST/"		
	fi
	if test ! $(grep -c -e "szHardDiskDirectory =/" <<<"$app") -eq  0  ; then 
		ligne=$(grep -e "szHardDiskDirectory =" <<<"$app")
		chaine=`cut -d= -f2 <<<"$ligne"`
		feuille=${chaine##*/}
		if test ! "$chkHDXT" -eq "0"; then
			app2=$(	eval "sed 's^szHardDiskDirectory =.*$^szHardDiskDirectory =../../../../../$feuille^g'<<<\"$app\"")
			app="$app2"
			# on enlève l'icône du lanceur. Pas évident.
			# Icône du dossier: fichier /Icon?  (2F 49 63 6F 6E 3F)  echo -e '\x2F\x49\x63\x6F\x6E\x3F'
			#marche au terminal, pas ici: rm "Armour11.adf.app/Icon"`echo -e '\x3F'` Heureusement, ça si:
			rm "$target/Icon"?
			#on constate que l'icône par défaut devient la appIcon.icns, qu'on modifie pour le fun
			cp  "$target/Contents/Resources/appiconIN.icns" "$target/Contents/Resources/appicon.icns"		
			#cp  -R "$chaine" "$target/Contents/Resources/AtariST/"		
			#mkdir "$Appdir/$feuille"
			#cp -R "$chaine/" "$Appdir/$feuille"
		else
			app2=$(	eval "sed 's^szHardDiskDirectory =.*$^szHardDiskDirectory =../AtariST/$feuille^g'<<<\"$app\"")
			app="$app2"
			cp -R "$chaine" "$target/Contents/Resources/AtariST"
		fi
	fi

	# Met AutoSave: Non.  Complique en fullscreen, Hatari alerte invisible s'il doit effacer l'ancien autosave 
#	app2=$(	eval "sed 's^bAutoSave = FALSE^bAutoSave = TRUE^g'<<<\"$app\"")
#	app="$app2"

	# Si on prefère avoir par défaut des touches curseur plutôt qu'un faux joystick 
	if test ! "$chkcursor" -eq "0"; then
		app2=$(	eval "sed 's^nJoystickMode = 2^nJoystickMode = 0^g'<<<\"$app\"")
		app="$app2"
	fi
	
	# Pour finir on copie app en app.cfg  vers la nouvelle Configurations
	echo "$app" > "$target/Contents/Resources/AtariST/CONFIGS/app.cfg"

	# Si on demande un demarrage sur hatarisav
	#if test ! "$chkdemar"  -eq "0"; then
	#if test "$chkdemar" = "Ne pas tenter d' utiliser \"hatari.sav\""; then echo "PAS HATARISAV"; fi
	if test "$chkdemar" = "Hack1: demarrer sur \"hatari.sav\""; then
		cp 	"$mypath/ScriptRelSav5.command" "$target/Contents/Resources/"
		/bin/echo -n --memstate \"\$AtariST/SAUVEGARDES/hatari+\" \> \/dev\/null 2\>\&1  >> "$target/Contents/Resources/script"
	fi
	if test "$chkdemar" = "Hack2: utiliser \"hatari.sav\" et HD"; then
		cp 	"$mypath/ScriptRelSav7.command" "$target/Contents/Resources/"
		/bin/echo -n --memstate \"\$AtariST/SAUVEGARDES/hatari+\" \> \/dev\/null 2\>\&1  >> "$target/Contents/Resources/script"
	fi

## -----------------ZONE APPLESCRIPT ------------------------ 
	# Si un écran de fond est indiquée on l'ajoute
	# Retire l'image par défaut à la routine du script
	rm "$target/Contents/Resources/hatarifondw.pdf"
	if test -e "$fond"  ; then
		cp  -R "$fond" "$target/Contents/Resources/hatarifondw.pdf"		
	fi

	# On complète la ligne de commande pour mettre Hatari devant, même en mode fenêtre (ce qui ferme la fenêtre de lancement Pashua, par chance)
	# On tape à la place de l'utilisateur pour résoudre le blocage d'alerte Tos 100 + disque dur, invisible en fullscreen {36, 36, 111, 36}=RETURN RETURN F12 RETURN
	if (test ! "$chkdemar" = "Ne pas tenter d' utiliser \"hatari.sav\"") && (test ! $(grep -c -e "szHardDiskDirectory =.*" <<<"$app") -eq  0 ) && (test $(grep -c -e "szTosImageFileName = ../AtariST/tos100fr.img" <<<"$app") -eq  1 ) && (test $(grep -c -e "bFullScreen = TRUE" <<<"$app") -eq  1 ) ; then
		/bin/echo -n " &  /usr/bin/osascript -e \"delay 2\" -e 'tell application \"System Events\"' -e 'tell process \"Hatari\"' -e 'set frontmost to true' -e \"key code {36, 36, 111, 36}\" -e \"end tell\" -e \"end tell\"  > /dev/null 2>&1 " >> $target/Contents/Resources/script
		echo "==========>> hatarisav+TOS100+fullscreen+HD"
	else
		# On complète la ligne de commande pour mettre Hatari devant, même en mode fenêtre (ce qui ferme la fenêtre de lancement Pashua, par chance)
		/bin/echo -n " > /dev/null 2>&1 & /usr/bin/osascript  -e 'tell application \"System Events\"' -e 'set frontmost of process \"Hatari\" to true'  -e \"end tell\"  > /dev/null 2>&1  " >> $target/Contents/Resources/script
	fi
#-------------------------------------------------------------
	exit 0
fi
#==================================================================================
# Creation d'une new.cfg
#==================================================================================
# On va dans Resources ou on a tout prepare
AtariST=$rsrcpath/AtariST
cd $AtariST
# Le debut: nettoyage et amorce en /tmp/new.cfg
rm SAUVEGARDES/auto.sav
rm CONFIGS/new.cfg
#cp CONFIGS/Myhatari.cfg /tmp/new.cfg
app=$(<CONFIGS/Myhatari.cfg)

# ECRAN
case "$popECRAN" in
	"Basse resolution")
	app2=$(	eval "sed 's^nMonitorType = 1^nMonitorType = 1^g'<<<\"$app\"")
	app="$app2"
   	;;
	"overscan Spectrum 512")
	app2=$(	eval "sed 's^bAllowOverscan = FALSE^bAllowOverscan = TRUE^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nSpec512Threshold = 16^nSpec512Threshold = 512^g'<<<\"$app\"")
	app="$app2"
    ;;
    "N&B Haute resolution")
	app2=$(	eval "sed 's^nMonitorType = 1^nMonitorType = 0^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nFrameSkips = 0^nFrameSkips = 1^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nVdiColors = 16^nVdiColors = 0^g'<<<\"$app\"")
	app="$app2"
 ;;
esac
if test ! "$chkVDI"  -eq "0" ; then
	app2=$(	eval "sed 's^bUseExtVdiResolutions = FALSE^bUseExtVdiResolutions = TRUE^g'<<<\"$app\"")
	app="$app2"
fi
if test ! "$chkfullscreen"  -eq "0" ; then
	app2=$(	eval "sed 's^bFullScreen = FALSE^bFullScreen = TRUE^g'<<<\"$app\"")
	app="$app2"
fi

# TOS
case "$popTOS" in
	"Atari ST Tos 1.00 (alerte HD)")
	app2=$(	eval "sed 's^szTosImageFileName = ../AtariST/tos106fr.img^szTosImageFileName = ../AtariST/tos100fr.img^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nMachineType = 1^nMachineType = 0^g'<<<\"$app\"")
	app="$app2"
  	;;
	"Atari ST Tos 1.04")
	app2=$(	eval "sed 's^szTosImageFileName = ../AtariST/tos106fr.img^szTosImageFileName = ../AtariST/tos104fr.img^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nMachineType = 1^nMachineType = 0^g'<<<\"$app\"")
	app="$app2"
  	;;
  	"Atari STE Tos 1.62")
	app2=$(	eval "sed 's^szTosImageFileName = ../AtariST/tos106fr.img^szTosImageFileName = ../AtariST/tos162fr.img^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nMachineType = 1^nMachineType = 1^g'<<<\"$app\"")
	app="$app2"
   	;;
  	"Atari STE Tos 2.06")
	app2=$(	eval "sed 's^szTosImageFileName = ../AtariST/tos106fr.img^szTosImageFileName = ../AtariST/tos206fr.img^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nMachineType = 1^nMachineType = 1^g'<<<\"$app\"")
	app="$app2"
   	;;
  	"Atari TT Tos 3.06")
	app2=$(	eval "sed 's^szTosImageFileName = ../AtariST/tos106fr.img^szTosImageFileName = ../AtariST/tos306fr.img^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nMachineType = 1^nMachineType = 2^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nCpuLevel = 0^nCpuLevel = 3^g'<<<\"$app\"")
	app="$app2"
   	;;
  	"Falcon Tos 4.04")
	app2=$(	eval "sed 's^szTosImageFileName = ../AtariST/tos106fr.img^szTosImageFileName = ../AtariST/tos404fr.img^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nMachineType = 1^nMachineType = 3^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^nCpuLevel = 0^nCpuLevel = 3^g'<<<\"$app\"")
	app="$app2"
   	;;
esac
#CLAVIER forcement dans le dossier AtariST (aussi dans MacProg.app)
if test -e "$CLAVIER"  ; then
	fichier=${CLAVIER##*/}
	app2=$(	eval "sed 's^szMappingFileName = ../AtariST/clavierFR.txt^szMappingFileName = ../AtariST/$fichier^g'<<<\"$app\"")
	app="$app2"
fi
#DISQUETTES
if test -e "$DISKA"  ; then
	app2=$(	eval "sed 's^szDiskAFileName =^szDiskAFileName =$DISKA^g'<<<\"$app\"")
	app="$app2"
fi
if test -e "$DISKB"  ; then
	app2=$(	eval "sed 's^szDiskBFileName =^szDiskBFileName =$DISKB^g'<<<\"$app\"")
	app="$app2"
fi

#DISQUE DUR DOSSIER
if test -d "$HDE"; then
	app2=$(	eval "sed 's^bBootFromHardDisk = FALSE^bBootFromHardDisk = TRUE^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^bUseHardDiskDirectory = FALSE^bUseHardDiskDirectory = TRUE^g'<<<\"$app\"")
	app="$app2"
	app2=$(	eval "sed 's^szHardDiskDirectory =^szHardDiskDirectory =$HDE^g'<<<\"$app\"")
	app="$app2"
fi

if test -e "$CART"  ; then
	app2=$(	eval "sed 's^szCartridgeImageFileName =^szCartridgeImageFileName =$CART^g'<<<\"$app\"")
	app="$app2"
fi

# Pour finir on recopie de tmp vers Configurations
echo "$app" > CONFIGS/new.cfg

#==================================================================================
#Execution
if test "$chkDoApp"  -eq "0" ; then 
	if test ! "$chkdemar"  -eq "0" ; then
		"Hatari.app/Contents/MacOS/Hatari" -c CONFIGS/new.cfg --memstate "$AtariST/SAUVEGARDES/hatari.sav" 
	else
		"Hatari.app/Contents/MacOS/Hatari" -c CONFIGS/new.cfg
	fi
fi
#==================================================================================
